package com.meida.module.bus.provider.service.impl;

import cn.hutool.log.StaticLog;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.module.bus.client.entity.BusWbsBudget;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsFileUtil;
import com.meida.module.bus.provider.mapper.BusWbsBudgetMapper;
import com.meida.module.bus.provider.service.BusWbsBudgetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 项目预算成本接口实现类
 *
 * @author flyme
 * @date 2020-11-12
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RefreshScope
public class BusWbsBudgetServiceImpl extends BaseServiceImpl<BusWbsBudgetMapper, BusWbsBudget> implements BusWbsBudgetService {
    @Value("${wbsTem}")
    private String wbsTem;

    @Autowired
    private PmsFileUtil pmsFileUtil;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusWbsBudget bwb, EntityMap extra) {
        return ResultBody.ok();
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusWbsBudget> cq, BusWbsBudget bwb, EntityMap requestMap) {
        cq.like(BusWbsBudget.class, "posid");
        cq.like(BusWbsBudget.class, "versn");
        cq.like(BusWbsBudget.class, "typps");
        cq.like(BusWbsBudget.class, "meeht");
        cq.like(BusWbsBudget.class, "ltext");
        cq.like(BusWbsBudget.class, "lpreis");
        cq.like(BusWbsBudget.class, "lpeinh");
        cq.orderByDesc("bwb.createTime");
        return ResultBody.ok();
    }

    @Override
    public void exportWbs(Map params, HttpServletRequest request, HttpServletResponse response) {
//        List<BusWbsBudget> busWbsBudgetList = Lists.newArrayList();
//        BusWbsBudget tt = new BusWbsBudget();
//        tt.setPosid("123");
//        busWbsBudgetList.add(tt);

        Collection<BusWbsBudget> busWbsBudgets = this.listByMap(params);
        if(0 < busWbsBudgets.size()) {
            // 文件輸出
            pmsFileUtil.exportFile(wbsTem, busWbsBudgets, ApiConstants.TMP_WBS_SAP, ApiConstants.TMP_WBS_SAP_OUT, response);
        }

//        InputStream is = null;
//        OutputStream os = null;
//        try {
//            is = new FileInputStream(tmpPath + ApiConstants.TMP_WBS_SAP);
//            os = new FileOutputStream(tmpPath + ApiConstants.TMP_WBS_SAP_OUT);
//            Context context = new Context();
//            List<BusWbsBudget> busWbsBudgetList = Lists.newArrayList();
//            BusWbsBudget tt = new BusWbsBudget();
//            tt.setPosid("123");
//            busWbsBudgetList.add(tt);
//            context.putVar("DATA", busWbsBudgetList);
//
//            //当循环的表体为javabean时指定读取的属性，Sheet2!A1表示输出开始的位置
//            JxlsHelper.getInstance().processTemplate(is, os, context);
//            response.reset();
//            response.setContentType("application/x-msdownload;charset=utf-8");
//            response.setHeader("Content-Disposition", "attachment;filename="+ new String((ApiConstants.TMP_WBS_SAP_OUT).getBytes("gbk"), "iso-8859-1"));//下载文件的名称
//            ServletOutputStream sout = response.getOutputStream();
//            byte[] bytes = FileUtil.readBytes(tmpPath + ApiConstants.TMP_WBS_SAP_OUT);
//            sout.write(bytes);
//            IoUtil.close(sout);
//
////            InputStream f = new FileInputStream(tmpPath + "wbsOutPut.xlsx");
////            bis = new BufferedInputStream(f);
////            bos = new BufferedOutputStream(sout);
////            byte[] buff = new byte[2048];
////            int bytesRead;
////            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
////                bos.write(buff, 0, bytesRead);
////            }
////            bos.flush();
////
////            IoUtil.close(bos);
////            IoUtil.close(bis);
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        } finally {
//            if (is != null){
//                try {
//                    is.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            if (os != null){
//                try {
//                    os.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
////            if(null != temp) {
////                temp.deleteOnExit();
////            }
//        }
    }

    private void setResponse(HttpServletResponse response, String filePath) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {

            response.reset();
            response.setContentType("application/x-msdownload;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("wbsOutPut.xlsx").getBytes("gbk"), "iso-8859-1"));//下载文件的名称
            ServletOutputStream sout = response.getOutputStream();

            InputStream f = new FileInputStream(filePath);
            bis = new BufferedInputStream(f);
            bos = new BufferedOutputStream(sout);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bos.flush();
            bos.close();
            bis.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            StaticLog.error(ex.getMessage());
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
